package com.ruoyi.maode.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.enums.ButtonEums;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.maode.domain.dto.AddButtonDTO;
import com.ruoyi.maode.domain.dto.QueryButtonDTO;
import com.ruoyi.maode.domain.entity.PartBpmnButton;
import com.ruoyi.maode.domain.vo.ApproveUserVO;
import com.ruoyi.maode.domain.vo.ButtonVO;
import com.ruoyi.maode.mapper.PartBpmnButtonMapper;
import com.ruoyi.maode.service.PartBpmnButtonService;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.core.config.ResultDTO;
import com.ruoyi.web.util.PageQuery;
import io.swagger.models.auth.In;
import org.apache.commons.math3.analysis.function.Add;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 零件审批按钮接口实现类
 * @author zhangwenqiang
 */
@Service
public class PartBpmnButtonServiceImpl extends ServiceImpl<PartBpmnButtonMapper, PartBpmnButton> implements PartBpmnButtonService {

    @Autowired
    private PartBpmnButtonMapper partBpmnButtonMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private SysRoleMapper sysRoleMapper;



    @Override
    public ResultDTO addButton(AddButtonDTO dto) {
        String buttonName = ButtonEums.getDescriptionByValue(dto.getButtonId());
        PartBpmnButton partBpmnButton = new PartBpmnButton();
        PartBpmnButton button = partBpmnButtonMapper.selectOne(new LambdaQueryWrapper<PartBpmnButton>()
                .eq(PartBpmnButton::getButtonId, dto.getButtonId())
                .eq(PartBpmnButton::getRoleId,dto.getRoleId()));
        if (button != null) {
            throw new UtilException("按钮已存在，请重新输入！");
        }
        partBpmnButton.setButtonId(dto.getButtonId());
        partBpmnButton.setButtonName(buttonName);
        partBpmnButton.setUserId(castString(dto.getUserIds()));
        partBpmnButton.setRoleId(dto.getRoleId());
        partBpmnButton.setCreateTime(new Date());
        partBpmnButton.setUpdateTime(new Date());
        int insert = partBpmnButtonMapper.insert(partBpmnButton);
        return insert > 0 ? ResultDTO.success("新增成功！") : ResultDTO.error("新增失败！");
    }

    @Override
    public int updateButton(AddButtonDTO dto) {
        PartBpmnButton partBpmnButton = new PartBpmnButton();
        partBpmnButton.setButtonId(dto.getButtonId());
        partBpmnButton.setButtonName(dto.getButtonName());
        partBpmnButton.setRoleId(dto.getRoleId());
        partBpmnButton.setUserId(castString(dto.getUserIds()));
        partBpmnButton.setUpdateTime(new Date());
        int update = partBpmnButtonMapper.update(partBpmnButton, new LambdaUpdateWrapper<PartBpmnButton>()
                .eq(PartBpmnButton::getId, dto.getId()));
        return update;
    }

    @Override
    public Page<ButtonVO> list(PageQuery<QueryButtonDTO> dto) {
        Page page = new Page<QueryButtonDTO>(dto.getPage(), dto.getPageSize());
        List<ButtonVO> buttonVOS = partBpmnButtonMapper.selectButtonList(dto.getData().getButtonName());
        List<ButtonVO> newButtons = new ArrayList<>();
        for (ButtonVO buttonVO :buttonVOS) {
            // 将人员id转换为List
            List<Integer> userIds = castList(buttonVO.getUserId());
            String names = "";
            for (Integer userId :userIds) {
                String nickName = sysUserService.selectUserById(Long.valueOf(userId)).getNickName();
                names = names + nickName + ",";
            }
            // 去掉末尾的","
            if (names.endsWith(",")) {
                names = names.substring(0, names.length() - 1);
            }
            buttonVO.setApproveUserName(names);
            // 获取角色名称
            SysRole role = sysRoleService.selectRoleById(buttonVO.getRoleId());
            buttonVO.setRoleName(role.getRoleName());
            newButtons.add(buttonVO);
        }
        page.setRecords(newButtons);
        page.setTotal(newButtons.size());
        return page;
    }

    @Override
    public ButtonVO selectButton(Long id) {
        ButtonVO buttonVO = partBpmnButtonMapper.selectButton(id);
        // 将人员id转换为List
        List<Integer> userIds = castList(buttonVO.getUserId());
        String names = "";
        for (Integer userId :userIds) {
            String nickName = sysUserService.selectUserById(Long.valueOf(userId)).getNickName();
            names = names + nickName + ",";
        }
        // 去掉末尾的","
        if (names.endsWith(",")) {
            names = names.substring(0, names.length() - 1);
        }
        buttonVO.setApproveUserName(names);
        // 获取角色名称
        SysRole role = sysRoleService.selectRoleById(buttonVO.getRoleId());
        buttonVO.setRoleName(role.getRoleName());
        return buttonVO;
    }

    @Override
    public List<ApproveUserVO> getApproveUser(Integer buttonId) {
        Long userId = SecurityUtils.getUserId();
        SysRole role = sysRoleMapper.selectRoleByUserId(userId);
        List<ApproveUserVO> approveUsers = partBpmnButtonMapper.getApproveUser(buttonId, role.getRoleId());
        return approveUsers;
    }

    @Override
    public List<ButtonVO> getApproveSubmit(Long roleId) {
        return partBpmnButtonMapper.getApproveSubmit(roleId);
    }

    /**
     * List<Integer>[1,2,3]转换为String"1,2,3"
     * @param list
     * @return
     */
    private String castString(List<Integer> list) {
        String result = String.join(",", list.stream().map(String::valueOf).toArray(String[]::new));
        return result;
    }

    /**
     * String"a,b,c"转换为List<String>["a","b","c"]
     * @param string
     * @return
     */
    private List<Integer> castList(String string) {
        List<Integer> list = Arrays.stream(string.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        return list;
    }
}
